﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace ZK.Qymd_TransManage
{
    public partial class AddAdmin : Form
    {
        public AddAdmin()
        {
            InitializeComponent();
        }

        private void AddAdmin_Load(object sender, EventArgs e)
        {
            Register re = new Register();
            re.LoadUsers();
        }

        private void txtId_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;

            if (e.KeyChar >= '0' && e.KeyChar <= '9')

            { e.Handled = false; }
            else if (e.KeyChar == 8)
            {
                e.Handled = false;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string id = txtId.Text;
            string name = txtName.Text;
            //string username = txtUsername.Text;
            string passWord = txtPassword.Text;
            if (id == "" || name == "" || passWord == "") {
                MessageBox.Show("账号，用户名或密码不能为空");
                return;
            }
            XmlDocument document = new XmlDocument();
            document.Load("UserData.xml");
            XmlElement root = document.DocumentElement;
            XmlElement userElement = document.CreateElement("user");
            XmlNode node = document.SelectSingleNode($"/users/user[@id = {id}]");
            XmlNodeList nodeList = document.SelectNodes("/users/user");
            foreach (XmlNode userNode in nodeList) {
                if (userNode.SelectSingleNode("name").InnerText == name) {
                    MessageBox.Show("用户名已重复");
                    return;
                }
            }
            if (node != null)
            {
                MessageBox.Show("id已重复");
            }
            //else if(name == username)
            //{
            //    MessageBox.Show("用户名已重复");
            //}
            else
            {
                userElement.SetAttribute("id", id);
                XmlElement nameElement = document.CreateElement("name");
                nameElement.InnerText = name;
                XmlElement passwordElement = document.CreateElement("password");
                passwordElement.InnerText = passWord;
                userElement.AppendChild(nameElement);
                userElement.AppendChild(passwordElement);
                root.AppendChild(userElement);
                document.Save("UserData.xml");
                MessageBox.Show("增添成功");
            }
        }
    }
}
